package com.itheima.reggie.common;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> handlerException(SQLIntegrityConstraintViolationException e){
    //    获取错误信息
        String message = e.getMessage();//Duplicate entry 'zhangsan' for key 'idx_username'
        //    解析出用户名
        String s = message.split(" ")[2];
        //    响应错误提示信息
        return R.error(s+"已存在，请不要重复添加");
    }

    /**
     * 异常处理方法
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> handlerException(CustomException e){

        return R.error(e.getMessage());
    }

}
